import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Main {

    private final static ReentrantLock mLock = new ReentrantLock();
    private final static Condition mLockCondition = mLock.newCondition();

    public static void main(String[] args) throws Exception{
       ;//启动HTTP服务线程

        try {
            final String ip = InetAddress.getLocalHost().getHostAddress();
            final int port = 9988;

            final HttpServer mHttpServer = new HttpServer(ip,port);
            mHttpServer.start();

            System.out.println("onCreate http start ok :" + mHttpServer.hostname + ":" + mHttpServer.myPort);
        }catch (Exception e){
            e.printStackTrace();
        }

        testHttpServer();


        try {
            mLock.lock();//堵塞主线程，避免HTTP服务进程退出
            mLockCondition.await();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            mLock.unlock();
        }

        System.out.println("finish service");
    }

    private static void testHttpServer() throws Exception{
        final String ip = InetAddress.getLocalHost().getHostAddress();
        final int port = 9988;
        final String baseUrl = "http://"+ip+":"+port+"/";

        String getFileListUrl = baseUrl+"getFileList?dirPath="+"F:\\APP\\tool";//获取指定文件夹的目录
        String downFileUrl = baseUrl+"getFile?fileName="+"F:\\APP\\tool\\test.txt";//下载指定文件
        String testUrl = baseUrl+"test";//测试HTTP服务，返回：调用成功

        URL url = new URL(testUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setAllowUserInteraction(false);
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));

        String line = "";
        while ((line = input.readLine()) != null){
            System.out.println(line);
        }
    }
}
